﻿using UnityEngine;
using System;
using System.Runtime.InteropServices;
using UnityEngine.EventSystems;
namespace QPEngine
{
    public class WindowBorderDrag : MonoBehaviour
    {
        const int SM_CXSCREEN = 0x00000000;
        const int SM_CYSCREEN = 0x00000001;
        const uint SWP_SHOWWINDOW = 0x0040;
        const int GWL_STYLE = -16;
        const int WS_BORDER = 1;
        const int WS_POPUP = 0x800000;
        public static IntPtr Handle;

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32.dll")]
        public static extern IntPtr SetWindowLong(IntPtr hwnd, int _nIndex, int dwNewLong);

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;//最左坐标
            public int Top; //最上坐标
            public int Right;//最右坐标
            public int Bottom; //最下坐标
        }
        static int winWidth;
        static int winHeight;
        static IntPtr WindIntPtr = IntPtr.Zero;
        public void Start()
        {
            winWidth = WindowBorderHide.instance.winWidth;
            winHeight = WindowBorderHide.instance.winHeight;
            WindIntPtr = WindowBorderHide.WindIntPtr;
        }

        public static void OnDrag()
        {
            ReleaseCapture();
            SendMessage(WindIntPtr, 0xA1, 0x02, 0);
            SendMessage(WindIntPtr, 0x0202, 0, 0);
        }

        public static void OnEndDrag()
        {
            //获取当前窗口句柄
            RECT rect = new RECT();
            GetWindowRect(WindIntPtr, ref rect);
            int winPosX = rect.Left;
            int winPosY = rect.Top;
            SetWindowLong(Handle, GWL_STYLE, WS_POPUP);
            SetWindowPos(WindIntPtr, 0, winPosX, winPosY, winWidth, winHeight, SWP_SHOWWINDOW);
        }

        ///// <summary>
        ///// 测试调用拖动
        ///// </summary>
        //public static bool bx = false;
        //public void Update()
        //{
        //    if (Input.GetMouseButtonDown(0)) { bx = true; }

        //    if (bx) { OnDrag(); }

        //    if (Input.GetMouseButtonUp(0))  { bx = false; OnEndDrag(); }
        //}

    }
}